package com.example.userbehaviorprediction;

import static android.content.ContentValues.TAG;

import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ReadDataService extends Service {
    public ReadDataService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "开始读取");
        readData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "停止读取");
    }

    public static String longToDate(long lo){
        Date date = new Date(lo);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sd.format(date);
    }

    public static String longToTime(long lo){
        String ms=(lo%1000+"ms");
        lo=lo/1000;
        String s=(lo%60+"s ");
        lo=lo/60;
        String m=(lo%60+"m ");
        lo=lo/60;
        String h=(lo+"h ");
        return h+m+s+ms;
    }

    public String getAppName(String str) {
        PackageInfo info = null;
        PackageManager pm = getPackageManager();
        try {
            info = pm.getPackageInfo(str,PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info.applicationInfo.loadLabel(pm).toString();

    }

    public void readData() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            try {
                startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
            } catch (Exception e) {
                //Toast.makeText(ReadDataService.this,"无法开启允许查看使用情况的应用界面",Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }

        UsageStatsManager usm = (UsageStatsManager)getSystemService(Context.USAGE_STATS_SERVICE);
        Calendar calendar = Calendar.getInstance();
        long endTime = calendar.getTimeInMillis();
        calendar.add(Calendar.DAY_OF_WEEK, -2);//
        long startTime = calendar.getTimeInMillis();
/**
 * 最近两周启动过所用app的List
 * queryUsageStats第一个参数是根据后面的参数获取合适数据的来源，有按天，按星期，按月，按年等。
 *  UsageStatsManager.INTERVAL_BEST
 *   UsageStatsManager.INTERVAL_DAILY 按天
 *   UsageStatsManager.INTERVAL_WEEKLY 按星期
 *   UsageStatsManager.INTERVAL_MONTHLY 按月
 *   UsageStatsManager.INTERVAL_YEARLY 按年
 */

        List<UsageStats> list = usm.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY,startTime,endTime);
//需要注意的是5.1以上，如果不打开此设置，queryUsageStats获取到的是size为0的list；
        if(list.size()==0)
        {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                try {
                    startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
                } catch (Exception e) {
                    //Toast.makeText(ReadDataService.this,"无法开启允许查看使用情况的应用界面",Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        }else{
            for(UsageStats usageStats :list){
                String name = usageStats.getPackageName();//获取包名
                //if (getAppName(name)!=null)
                  //  name = getAppName(name);
                //if(name.contains("com")||name.contains("google")) continue;
                //usageStats.getFirstTimeStamp();//获取第一次运行的时间
                //usageStats.getLastTimeStamp();//获取最后一次运行的时间
                //usageStats.getTotalTimeInForeground();//获取总共运行的时间
                //Log.e(TAG, "name: " + name);

                SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(ReadDataService.this);
                SQLiteDatabase readableDatabase = helper.getReadableDatabase();
                SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                if (readableDatabase.isOpen()) {
                    Cursor cursor = readableDatabase.rawQuery(String.format("select * from appUse where name = '%s'", name), null);
                    if(cursor.moveToNext()) {
                        String sql = "delete from appUse where name = ?";
                        writableDatabase.execSQL(sql, new Object[]{name});
                        writableDatabase.close();
                    }
                    cursor.close();
                    readableDatabase.close();
                }
//                Log.e("name:",name);
//                Log.e("FirstTime:",longToDate(usageStats.getFirstTimeStamp()+8*3600*1000)); //第一次启动时间
//                Log.e("LastTime:",longToDate(usageStats.getLastTimeStamp()+8*3600*1000)); //最近一次启动时间
//                Log.e("TotalTime:",longToTime(usageStats.getTotalTimeInForeground())); //总时间
                String firstTime = longToDate(usageStats.getFirstTimeStamp()+8*3600*1000);
                String lastTime = longToDate(usageStats.getLastTimeStamp()+8*3600*1000);
                String totalTime = longToTime(usageStats.getTotalTimeInForeground());
                int times = 0;
                try{
                    Field field = usageStats.getClass().getDeclaredField("mLaunchCount");//获取应用启动次数，UsageStats未提供方法来获取，只能通过反射来拿到
                    field.setAccessible(true);
                    times = field.getInt(usageStats);//启动次数
                }catch (Exception e)
                {
                    e.printStackTrace();;
                }
                writableDatabase = helper.getWritableDatabase();
                if (writableDatabase.isOpen()) {
                    String sql = "insert into appUse(name, firstTime, lastTime, totalTime, times) values(?,?,?,?,?)";
                    writableDatabase.execSQL(sql, new Object[]{name, firstTime, lastTime, totalTime, times});
                    writableDatabase.close();
                }
            }
        }
    }
}